import telnetlib
import logging
import schedule
import time
from daily_checker.performance_runner import run_performance_monitor
import asyncio

# 初始化日志模块
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')


def do_auto_script():
    try:
        # 使用telnetlib 创建一个telnet链接
        tn = telnetlib.Telnet(HOST, PORT)
        tn.read_until(b"login: ")
        tn.write((USER.encode('ascii')).replace(b'\n', b''))
        tn.read_until(b"Password: ")
        tn.write((PASSWORD.encode('ascii')).replace(b'\n', b''))

        # 执行COMMAND1 和 COMMAND2
        tn.write(COMMAND1.encode('ascii') + b"\n")
        tn.write(COMMAND2.encode('ascii') + b"\n")

        # 等待命令执行完成（这里假设有一个明确的结束标志，可以根据实际情况调整）
        tn.read_until(b"some_end_of_command_indicator")

        tn.close()
        logging.info("Telnet script execution completed.")
    except Exception as ex:
        logging.error(f"Error occurred during telnet script execution: {ex}")


async def async_do_auto_script():
    # 异步包装do_auto_script函数，由于telnetlib不支持异步，这里使用loop.run_in_executor将任务放入线程池执行
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, do_auto_script)


async def async_run_performance_monitor(identifier, duration, interval):
    # 异步化run_performance_monitor函数
    await run_performance_monitor(identifier, duration, interval)


async def async_job():
    task1 = asyncio.create_task(async_do_auto_script())
    task2 = asyncio.create_task(async_run_performance_monitor('NQ10-99', 10, 1))
    await asyncio.gather(task1, task2)


def job():
    asyncio.run(async_job())


if __name__ == '__main__':
    HOST = '192.168.2.98'
    PORT = 23  # 端口号应为整数类型
    USER = "root"
    PASSWORD = "vp202401"
    COMMAND1 = "cd /tmp/nvr_auto_script/functional_test/testcases"
    COMMAND2 = "./run_all_script.sh"
    do_auto_script()
    # 定义每天早上8:00执行一次job()
    # schedule.every().day.at("18:21").do(job)
    #
    # while True:
    #     schedule.run_pending()
    #     time.sleep(1)
